<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Users
 *
 * This model represents user authentication data. It operates the following tables:
 * - user account data,
 * - user profiles
 *
 * @package	Tank_auth
 * @author	Ilya Konyukhov (http://konyukhov.com/soft/)
 */
class Clientmodel extends CI_Model
{

	private $view_name = 'clients';
	private $raw_name  = 'user_profiles';

	function __construct()
	{
		parent::__construct();
		
	}

	function getAllByOwnerId($id,$sortname='',$sortorder='',$qtype='',$query='',$page='',$rp='')
	{
		$this->db->select($this->view_name.'.* , SUM(`invoices`.`balance`) AS `balance`');
		$this->db->from($this->view_name);
		$this->db->join('invoices',$this->view_name.'.id=invoices.client_id','left');
		$this->db->where($this->view_name.'.owner_id',$id);
		$this->db->group_by($this->view_name.'.id');
		if($sortname != '' && $sortorder != ''){
			$this->db->order_by($this->view_name.'.'.$sortname,$sortorder);
		}
		if($qtype != '' && $query != ''){
			$this->db->where($qtype,$query);
		}
		if($rp != ''){
			if($page != ''){
				$this->db->limit($rp,($page-1)*$rp);
			} else {
				$this->db->limit($rp);
			}
		}
		$q = $this->db->get();
		return $q->result();
	}

	function getCountByOwnerId($id,$qtype='',$query=''){
		$this->db->select('COUNT(*) AS `total`');
		$this->db->from($this->view_name);
		$this->db->where('owner_id',$id);
		if($qtype != '' && $query != ''){
			$this->db->where($qtype,$query);
		}
		
		$q = $this->db->get();
		$q = $q->row(0);
		return $q->total;
	}

	function getBalance($client_id,$owner_id=false){
		$this->db->select('SUM(`invoices`.`balance`) AS `balance`');
		if($owner_id){
			$this->db->where('owner_id',$owner_id);
		}
		$this->db->where('client_id',$client_id);
		$q = $this->db->get('invoices');
		if($q->num_rows()>0){
			return $q->row()->balance;
		} else {
			return 0;
		}
	}

	function getByClientId($client_id){
		$this->db->where('id',$client_id);
		$q = $this->db->get($this->view_name);
		return $q->result();
	}

	function addClient($data){
		$data['uuid']=uniqid('',true);
		$this->db->insert('client_requests',$data);
		return $data;
	}
	
	function updateClient($profile_id,$data){
		$this->db->where('id',$profile_id);
		return $this->db->update($this->raw_name,$data);
	}

}
